package com.np.windowmanagerdemo1;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PictureInPictureParams;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Rational;
import android.widget.TextView;
import android.widget.Toast;

public class PictureInPictureActivity extends AppCompatActivity {

    private TextView mTvPip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_in_picture);

        mTvPip = findViewById(R.id.tv_pip);
        mTvPip.setOnClickListener(v -> {
            if (isCanPipModel()) {
                enterPipModel();
            } else {
                Toast.makeText(this, "无法使用PIP模式", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean isCanPipModel() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
    }

    private void enterPipModel() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder();
            builder.setAspectRatio(new Rational(10, 5));
            enterPictureInPictureMode(builder.build());
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, @NonNull Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        if (isInPictureInPictureMode) {
            mTvPip.setText("画中画模式");
        } else {
            mTvPip.setText("正常模式");
        }
    }
}